<template>
  <el-drawer
    :visible.sync="$store.state.process.approverDrawer"
    :with-header="false"
    :before-close="beforeClose"
    size="700px"
    @open="openDrawer">
    <div class="title">
      <Title title="节点设置" />
      <i class="icon el-icon-close" @click="beforeClose()"/>
    </div>
    <div class="content">
      <!-- 角色列表 -->
      <SelectRoleUser
        v-model="approverDrawerData.examineRoles"
        :error-roles-ids="errorRolesIds"
        :type="type"
        @removeError="removeError" />
      <!-- 自定义表单-节点前置条件设置 -->
      <template v-if="!isFixed">
        <Title title="前置条件" style="margin-top: 32px">
          <span class="title-tip">前置条件仅对人员必填勾选项生效</span>
        </Title>
        <el-form class="top-content" label-width="68px">
          <el-form-item label="规则类型" prop="frontRole">
            <selectWithoutHttp v-model="approverDrawerData.frontRole" :list-data="ruleOptions" class="width100" />
          </el-form-item>
        </el-form>
        <div class="filter-scroll">
          <div
            v-for="(item, index) in approverDrawerData.frontFilterList"
            :key="index"
            :class="{'last': approverDrawerData.frontFilterList.length - 1 === index}"
            class="filter-item">
            <FilterValue
              :filter-item="item"
              :field-list="fieldList"
              :is-show-status="false"
              has-value-type
              key-name="filterField" />
            <div class="btn-list">
              <img :src="copyGroupIcon" title="复制" class="copy-icon" alt="" @click="copyItem(item)">
              <img :src="deleteGroupIcon" title="删除" class="delete-icon" alt="" @click="deleteItem(index)">
            </div>
          </div>
        </div>
        <div :style="!approverDrawerData.frontFilterList || approverDrawerData.frontFilterList.length ===0?{marginTop: 0}:''" style="margin-bottom: 32px" class="footer-bar">
          <div class="add-btn" @click="addFilter">添加条件 <i class="add-icon el-icon-plus" /></div>
          <div class="tip">最多添加20条</div>
        </div>
      </template>
      <!-- 其他设置 -->
      <OtherOptions :approver-drawer-data="approverDrawerData" :process-list="processList" style="margin-bottom: 16px;" />
      <div class="timeout-item">
        <el-checkbox v-model="approverDrawerData.isOpenTimeOut" :true-label="1" :false-label="0" class="checkbox" @change="timeoutChange(approverDrawerData)"><span class="check-span">审批超时提醒</span></el-checkbox>
        <template v-if="approverDrawerData.isOpenTimeOut">
          <el-input-number
            :class="{'isError': getError('openTimeOut').msg}"
            v-model="approverDrawerData.timeOut"
            :min="1"
            :max="10000"
            :precision="0"
            size="small"
            class="timeout-item-input"
            label=""
            @input="removeError"/>
          <span class="timeout-tip">小时后</span>
          <selectWithoutHttp v-model="approverDrawerData.timeOutType" :list-data="timeOutTypeOptions" class="width-120" label-name="label" key-name="value" placeholder="请选择提醒类型" @change="removeError" />
        </template>
        <div v-if="getError('openTimeOut').msg" :style="{left: getError('openTimeOut').left || 0}" class="error-tool">{{ getError('openTimeOut').msg }}</div>
      </div>
      <!-- 审批超时任务 -->
      <div class="timeout-item">
        <el-checkbox v-model="approverDrawerData.isRedirectTimeOut" :true-label="1" :false-label="0" class="checkbox" @change="redirectChange(approverDrawerData)"><span class="check-span">审批超时任务</span></el-checkbox>
        <template v-if="approverDrawerData.isRedirectTimeOut">
          <div style="position: relative;">
            <el-input-number
              v-model="approverDrawerData.redirectTimeOut"
              :class="{'isError': getError('redirectTimeOut').msg}"
              :min="0.1"
              :max="10000"
              :precision="1"
              size="small"
              class="timeout-item-input"
              label=""
              @input="removeError"/>
            <div v-if="getError('redirectTimeOut').msg" :style="{left: 0, width: '100%'}" class="error-tool">{{ getError('redirectTimeOut').msg }}</div>
          </div>
          <span class="timeout-tip">小时后</span>
          <selectWithoutHttp v-model="approverDrawerData.timeOutTaskType" :list-data="timeOutTaskTypeOptions" style="width: 100px;" label-name="label" key-name="value" placeholder="请选择提醒类型" @change="removeError" />
          <div v-if="approverDrawerData.timeOutTaskType === 1 || approverDrawerData.timeOutTaskType === 2" class="flex-display">
            <selectWithoutHttp v-model="approverDrawerData.transferRoleType" :list-data="transferRoleTypeOptions" class="width-160" label-name="name" key-name="id" placeholder="请选择审批角色" @change="removeError" />
            <!-- 选择自定义人员：2 -->
            <select-custom-user v-if="approverDrawerData.transferRoleType === ROLE_TYPE.CUSTOMIZE" :is-error="!!getError('transferdiyUser').msg" v-model="approverDrawerData.transferDiyUserIdList" :diy-user-item-list.sync="approverDrawerData.transferDiyUserList" class="ml12" placeholder="请选择人员" @change="removeError" />
            <!-- 选择部门：1 -->
            <selectDepart v-if="approverDrawerData.transferRoleType === ROLE_TYPE.DEPARTMENT" :class="{'isError': getError('transferdept').msg}" v-model="approverDrawerData.transferDepartmentIdList" class="width-240 ml12" @change="removeError" />
            <!-- 主管：5 -->
            <selectWithoutHttp v-if="approverDrawerData.transferRoleType === ROLE_TYPE.DIRECTOR" :class="{'isError': getError('transfermanage').msg}" v-model="approverDrawerData.transferManageRole" :list-data="manageRoleType" class="width-160 ml12" label-name="name" key-name="id" placeholder="主管类型" @change="removeError"/>
            <!-- 指定人员选择字段：7 -->
            <selectWithoutHttp
              v-if="approverDrawerData.transferRoleType === ROLE_TYPE.DESIGNATE"
              v-model="approverDrawerData.designateUserSelect"
              :class="{'isError': getError('transfer' + ROLE_TYPE.DESIGNATE).msg}"
              :list-data="allUserFields"
              clearable
              class="width-160 ml12"
              label-name="name"
              key-name="key"
              placeholder="请选择"
              @change="removeError" />
            <!-- 角色组：9 -->
            <selectWithoutHttp
              v-if="approverDrawerData.transferRoleType === ROLE_TYPE.ROLE_GROUP"
              v-model="approverDrawerData.roleGroup"
              :class="{'isError': getError('transfer' + ROLE_TYPE.ROLE_GROUP).msg}"
              :list-data="roleGroupList"
              :key="'transfer' + ROLE_TYPE.ROLE_GROUP"
              clearable
              class="width-160 ml12"
              label-name="name"
              key-name="id"
              placeholder="请选择"
              @change="removeError" />
            <!-- 获取BP指定审批人：10 -->
            <template v-if="approverDrawerData.transferRoleType === ROLE_TYPE.BP_APPROVER">
              <selectWithoutHttp
                v-model="approverDrawerData.bpNames"
                :class="{'isError': !approverDrawerData.bpNames || !approverDrawerData.bpNames.length && getError('transfer' + ROLE_TYPE.BP_APPROVER).msg}"
                :key="'transfer' + ROLE_TYPE.BP_APPROVER"
                :list-data="BPList"
                :filterable="false"
                class="width-160 ml12"
                placeholder="请选择BP类型"
                key-name="name"
                label-name="name"
                collapse-tags
                multiple
                clearable
                @change="removeError"
              />
              <selectWithoutHttp
                v-if="approverDrawerData.bpNames && approverDrawerData.bpNames.length"
                v-model="approverDrawerData.bpDepts"
                :class="{'isError': getError('transfer' + ROLE_TYPE.BP_APPROVER).msg}"
                :list-data="allDeptFields"
                :filterable="false"
                class="width-160 ml12"
                placeholder="请选择"
                key-name="key"
                label-name="name"
                collapse-tags
                multiple
                clearable
                @change="removeError"
              />
            </template>
            <!-- 转交欠款-指定人员字段：12 -->
            <selectWithoutHttp
              v-if="approverDrawerData.transferRoleType === ROLE_TYPE.ARREARS_USERS"
              :class="{'isError': getError('transfer' + ROLE_TYPE.ARREARS_USERS).msg}"
              v-model="approverDrawerData.transferRole"
              :list-data="transferRoleType"
              class="width-160 ml12"
              label-name="name"
              key-name="id"
              placeholder="请选择"
              @change="removeError"/>
            <!-- 指定人员主管：14 -->
            <template v-if="approverDrawerData.transferRoleType === ROLE_TYPE.DESIGNATE_DIRECTOR">
              <selectWithoutHttp
                v-model="approverDrawerData.designateDirectorUser"
                :class="{'isError': !approverDrawerData.designateDirectorUser && getError('transfer' + ROLE_TYPE.DESIGNATE_DIRECTOR).msg}"
                :key="'transfer' + ROLE_TYPE.DESIGNATE_DIRECTOR"
                :list-data="allUserFields"
                clearable
                class="width-160 ml12"
                label-name="name"
                key-name="key"
                placeholder="请选择"
                @change="removeError" />
              <selectWithoutHttp
                v-if="approverDrawerData.designateDirectorUser"
                v-model="approverDrawerData.designateDirector"
                :class="{'isError': getError('transfer' + ROLE_TYPE.DESIGNATE_DIRECTOR).msg}"
                :list-data="manageRoleType"
                class="width-160 ml12"
                label-name="name"
                key-name="id"
                placeholder="主管类型"
                @change="removeError"/>
            </template>
            <div v-if="getError('transferdept').msg" :style="{left: getError('transferdept').left || 0}" class="error-tool">{{ getError('transferdept').msg }}</div>
            <div v-if="getError('transferdiyUser').msg" :style="{left: getError('transferdiyUser').left || 0}" class="error-tool">{{ getError('transferdiyUser').msg }}</div>
            <div v-if="getError('transfermanage').msg" :style="{left: getError('transfermanage').left || 0}" class="error-tool">{{ getError('transfermanage').msg }}</div>
            <div v-if="getError('transfer' + ROLE_TYPE.DESIGNATE).msg" :style="{left: getError('transfer' + ROLE_TYPE.DESIGNATE).left || 0}" class="error-tool">{{ getError('transfer' + ROLE_TYPE.DESIGNATE).msg }}</div>
            <div v-if="getError('transfer' + ROLE_TYPE.ROLE_GROUP).msg" :style="{left: getError('transfer' + ROLE_TYPE.ROLE_GROUP).left || 0}" class="error-tool">{{ getError('transfer' + ROLE_TYPE.ROLE_GROUP).msg }}</div>
            <div v-if="getError('transfer' + ROLE_TYPE.BP_APPROVER).msg" :style="{left: getError('transfer' + ROLE_TYPE.BP_APPROVER).left || 0}" class="error-tool">{{ getError('transfer' + ROLE_TYPE.BP_APPROVER).msg }}</div>
            <div v-if="getError('transfer' + ROLE_TYPE.ARREARS_USERS).msg" :style="{left: getError('transfer' + ROLE_TYPE.ARREARS_USERS).left || 0}" class="error-tool">{{ getError('transfer' + ROLE_TYPE.ARREARS_USERS).msg }}</div>
            <div v-if="getError('transfer' + ROLE_TYPE.DESIGNATE_DIRECTOR).msg" :style="{left: getError('transfer' + ROLE_TYPE.DESIGNATE_DIRECTOR).left || 0}" class="error-tool">{{ getError('transfer' + ROLE_TYPE.DESIGNATE_DIRECTOR).msg }}</div>
          </div>
          <selectWithoutHttp v-else v-model="approverDrawerData.redirectType" :list-data="redirectTypeOptions" class="width-120 ml12" label-name="label" key-name="value" placeholder="请选择提醒类型" @change="removeError" />
        </template>

      </div>
      <div class="one-cell mt18">
        <div class="options-content" style="color: #666;margin-right:10px;">设置审批事件</div>
        <selectWithoutHttp
          v-model="approverDrawerData.setEvents"
          :list-data="eventList"
          class="width-240 event-box"
          label-name="label"
          key-name="value"
          multiple
          collapse-tags
          placeholder="请选择开启事件"
          @change="handelChangeEvent(approverDrawerData)" />
      </div>
      <div class="explanation">
        <div class="label">节点审批说明：</div>
        <div class="ellipsisOne explanation-content"><i class="el-icon-edit-outline" style="cursor:pointer;" @click="openExplateDialog(approverDrawerData)"/>{{ approverDrawerData.explanation || '--' }}</div>
      </div>
      <div class="explanation">
        <div class="label">审批弹窗说明：</div>
        <div class="ellipsisOne explanation-content"><i class="el-icon-edit-outline" style="cursor:pointer;" @click="openExplateDialog(approverDrawerData, 1)"/>{{ approverDrawerData.approvalExplanation || '--' }}</div>
      </div>
      <div class="explanation">
        <div class="label">提交按钮配置：</div>
        <span v-if="approverDrawerData.submitBtnList && approverDrawerData.submitBtnList.length" class="label" style="color: #31CC9C">已配置</span>
        <span v-else class="label">未配置</span>
        <div class="button-text btn-config">
          <div class="label" style="margin-left: 6px" @click="oepnDialog">点击配置</div>
          <el-tooltip :open-delay="1000" content="配置审批同意弹窗提交按钮及下个节点审批人" placement="top">
            <tipIcon is-diy />
          </el-tooltip>
        </div>
      </div>
      <explateDialog ref="explateDialog" :title-name="explateDialogTitle" @setExplanation="setExplanation" />
      <SubmitBtnConfig ref="SubmitBtnConfig" :type="type" @setSubmitBtnConfig="setSubmitBtnConfig" />
    </div>
  </el-drawer>
</template>

<script>
import { mapState } from 'vuex';
// import { EventBus } from '@/utils/eventBus';
import ElMessage from '@/utils/message';
import Title from '@/components/Title';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import FilterValue from './filterValue';
// components
import selectCustomUser from '../model/selectCustomUser';
import selectDepart from '../model/selectDepart';
import explateDialog from '../model/explateDialog';
import SelectRoleUser from './selectRoleUser';
import OtherOptions from './OtherOptions';
import SubmitBtnConfig from './SubmitBtnConfig';
import deleteGroupIcon from '@/assets/legalProcess/deleteIcon.png';
import copyGroupIcon from '@/assets/legalProcess/copyIcon.png';
import { EVENT_TYPE, FIXED_PROCESS_TYPE, ROLE_TYPE } from '@/utils/const/process';
import { forEachFormOptions } from '@/utils/formMakeUtils.js';

export default {
  components: {
    Title,
    selectWithoutHttp,
    selectCustomUser,
    selectDepart,
    explateDialog,
    OtherOptions,
    SelectRoleUser,
    SubmitBtnConfig,
    FilterValue
  },
  props: {
    type: {// 增加type判断，避免不同环境id改变
      type: Number,
      default: 0
    },
    processList: {
      type: Object,
      default: () => ({})
    },
    eventNames: {
      type: Array,
      default: () => []
    },
    customFormList: {
      type: Array,
      default: () => []
    },
    isFixed: { // 是否为固定表单
      type: Boolean,
      default: false
    },
    fixedId: {
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      deleteGroupIcon,
      copyGroupIcon,
      ROLE_TYPE,
      manageRoleType: [
        { id: 0, name: '当前部门主管' },
        { id: 1, name: '部门上级主管' },
        { id: 2, name: '部门最高主管' }
      ],
      timeOutTypeOptions: [
        { value: 0, label: '仅提醒一次' },
        { value: 1, label: '每小时提醒一次' },
        { value: 2, label: '每4小时提醒一次' },
        { value: 3, label: '每天提醒一次' },
        { value: 4, label: '每周提醒一次' },
        { value: 5, label: '每月提醒一次' }
      ],
      redirectTypeOptions: [
        // 【v2.9.7】跳转类型  0:上一步 1: 第一步 2:展示流程配置的所有节点
        { value: 0, label: '上一步' }
        // { value: 1, label: '第一步' },
        // { value: 2, label: '展示流程配置的所有节点' }
      ],
      timeOutTaskTypeOptions: [{ value: 0, label: '跳转至' }, { value: 1, label: '转交至' }, { value: 2, label: '通知至' }],
      errorRolesIds: [],
      events: [
        { value: EVENT_TYPE.TURN_ON_CONTRACT_RECYCLING, label: '开启合同回收' },
        { value: EVENT_TYPE.OPEN_CONTRACT_NO_GENERATE, label: '开启合同编号生成' },
        { value: EVENT_TYPE.AFTER_NODE_GENERATE_ARCHIVE_CODE, label: '节点之后生成归档编号' },
        { value: EVENT_TYPE.BUSINESS_RECYCLE_CONTRACT, label: '业务回收合同' },
        { value: EVENT_TYPE.OPEN_STAMP_TYPE, label: '开启盖章类型填写' }
      ],
      explateDialogTitle: '',
      fieldList: [],
      customEventList: []
    };
  },
  computed: {
    ...mapState({
      'approverDrawerData': state => state.process.approverDrawerData,
      'roleGroupList': state => state.formMake.roleGroups,
      'allUserFields': state => state.formMake.allUserFields,
      'BPList': state => state.formMake.BPList,
      'allDeptFields': state => state.formMake.allDeptFields
    }),
    normalRoleType() {
      return [
        { id: ROLE_TYPE.CREATOR, name: '任务创建人' },
        { id: ROLE_TYPE.DEPARTMENT, name: '选择部门' },
        { id: ROLE_TYPE.CUSTOMIZE, name: '自定义人员' },
        { id: ROLE_TYPE.PROPOSER, name: '申请人' },
        { id: ROLE_TYPE.DIRECTOR, name: '主管' },
        { id: ROLE_TYPE.DESIGNATE, name: '指定人员选择字段' },
        { id: ROLE_TYPE.DESIGNATE_DIRECTOR, name: '指定人员主管' },
        { id: ROLE_TYPE.CREATOR_SUPERIOR, name: '创建人直属上级' },
        { id: ROLE_TYPE.ROLE_GROUP, name: '角色组' },
        { id: ROLE_TYPE.BP_APPROVER, name: '获取BP指定审批人' }
      ];
    },
    transferRoleType() {
      return [
        { id: 0, name: '转交人' },
        { id: 1, name: '被转交人' }
      ];
    },
    transferRoleTypeOptions() {
      // 签约内审、申请原件、自定义审批不能选择申请人
      const { isFixed } = this.$route.query;
      if (!isFixed) { // 自定义审批
        return this.normalRoleType.filter(i => i.id !== ROLE_TYPE.PROPOSER);
      } else if ([FIXED_PROCESS_TYPE.SIGN_UP, FIXED_PROCESS_TYPE.APPLY_ORIGINAL].includes(this.type)) { // 签约内审、申请原件
        return this.normalRoleType.filter(i => ![ROLE_TYPE.PROPOSER, ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(i.id));
      } else if (this.type === FIXED_PROCESS_TYPE.EFFORT_ALLOCATION) { // 精力分配
        return this.normalRoleType.filter(i => ![ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(i.id));
      } else if (this.type === FIXED_PROCESS_TYPE.ARREARS_TRANSFER) { // 转交欠款
        const list = this.normalRoleType.filter(i => ![ROLE_TYPE.PROPOSER, ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(i.id));
        return [...list, { id: ROLE_TYPE.ARREARS_USERS, name: '指定人员字段' }];
      } else if (this.type === FIXED_PROCESS_TYPE.TERMINATION) {
        return this.normalRoleType.filter(i => {
          return ![ROLE_TYPE.PROPOSER, ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(i.id);
        });
      } else if (this.type === FIXED_PROCESS_TYPE.EXTERNALHARVEST) { // 外采额度申请
        const list = this.normalRoleType.filter(i => ![ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(i.id));
        return [...list, { id: ROLE_TYPE.AUTHUSER, name: '授权人' }];
      } else { // 其他固定表单
        return this.normalRoleType.filter(i => ![ROLE_TYPE.DESIGNATE, ROLE_TYPE.DESIGNATE_DIRECTOR].includes(i.id));
      }
    },
    eventList() { // 不同类型的流程获取不同的对应事件列表
      // 自定义表单
      if (!this.isFixed) {
        return this.eventNames;
      }
      if (this.type === FIXED_PROCESS_TYPE.PAYMENT_APPLY) {
        return [ // 请款流程开启事件
          { value: EVENT_TYPE.OPEN_INVOICE_EDIT, label: '开启发票填写' },
          { value: EVENT_TYPE.OPEN_AUTO_CONFIRM_PAY, label: '自动确认付款' },
          { value: EVENT_TYPE.EDIT_EXPLAIN, label: '编辑说明' }, // v3.0.4 新增，当开启该事件时，可编辑结算单名称、备注、收款列表说明
          { value: EVENT_TYPE.OPEN_PAY_TIME, label: '开启支付日期填写' }, // v3.2.4新增，当开启该事件时，可编辑计划支付日期和实际支付日期
          { value: EVENT_TYPE.BUSINESS_ACCOUNTING, label: '业务会计审批节点' } // v3.2.9新增，用来标记业务会计审批节点
        ];
      }
      if (this.type === FIXED_PROCESS_TYPE.INVOICE_APPLY) {
        return [ // 开票申请开启事件
          { value: EVENT_TYPE.INVOICE_APPLY_EDIT_INVOICE, label: '开启发票填写' },
          { value: EVENT_TYPE.RELEATE_FINANCE_TXN, label: '关联到账流水' },
          { value: EVENT_TYPE.INVALID_INVOICE, label: '节点后可作废发票' }
        ];
      }
      if (this.type === FIXED_PROCESS_TYPE.EFFORT_ALLOCATION) {
        return [{ value: EVENT_TYPE.FORM_EDIT, label: '表单编辑' }];
      }
      if ([FIXED_PROCESS_TYPE.APPLY_ORIGINAL,
        FIXED_PROCESS_TYPE.INVOICE_ABANDON,
        FIXED_PROCESS_TYPE.ARREARS_TRANSFER,
        FIXED_PROCESS_TYPE.UP_ONLINE,
        FIXED_PROCESS_TYPE.TERMINATION,
        FIXED_PROCESS_TYPE.CUSTOMER_ADJUSTMENT,
        FIXED_PROCESS_TYPE.BLOGGER_FILTER].includes(this.type)) {
        return [];
      }
      if (this.type === FIXED_PROCESS_TYPE.REIMBURSEMENT || this.type === FIXED_PROCESS_TYPE.BORROW_APPLY) {
        return [
          { value: EVENT_TYPE.EDIT_EXPLAIN, label: '编辑说明' },
          { value: EVENT_TYPE.OPEN_PAY_TIME, label: '开启支付日期填写' }
        ];
      }
      if (this.type === FIXED_PROCESS_TYPE.REPAY_APPLY) {
        return [
          { value: EVENT_TYPE.EDIT_EXPLAIN, label: '编辑说明' }
          // { value: EVENT_TYPE.SNAPSHOT_AMOUNT_OWED, label: '快照欠款金额' }
        ];
      }
      if (this.type === FIXED_PROCESS_TYPE.SIGN_UP) { // 签约内审
        return [
          { value: EVENT_TYPE.SYNC_ACCOUNT, label: '同步资源' },
          { value: EVENT_TYPE.ASSOCIATE_CONTRACT, label: '关联合同' }
        ];
      }
      if (this.type === FIXED_PROCESS_TYPE.EXTERNALHARVEST) {
        // 外采额度申请
        return [
          { value: EVENT_TYPE.AUTHUSER_EDIT, label: '开启修改授权人' }
        ];
      }
      return this.events;
    },
    ruleOptions() {
      return [
        { id: 0, value: '符合以下全部条件' },
        { id: 1, value: '符合以下任一条件' }
      ];
    }
  },
  methods: {
    openDrawer() {
      if (this.approverDrawerData && this.approverDrawerData.setEvents && this.approverDrawerData.setEvents.length) {
        const ids = this.eventList.map(i => i.value);
        this.approverDrawerData.setEvents = this.approverDrawerData.setEvents.filter(i => {
          return ids.includes(i);
        });
      }
      // 自定义表单设置
      if (!this.isFixed) {
        if (!this.approverDrawerData.frontRole && this.approverDrawerData.frontRole !== 0) {
          this.$set(this.approverDrawerData, 'frontRole', 0);
        }
        this.initFieldList();
      }
      this.resetDesignateUserSelect();
    },
    // 清除指定人员角色/部门选中项中表单已删除的人员选择组件
    resetDesignateUserSelect() {
      this.$nextTick(() => {
        const { examineRoles, designateUserSelect, bpDepts, bpNames, designateDirectorUser } = this.approverDrawerData;
        if (Array.isArray(examineRoles) && examineRoles.length) {
          examineRoles.forEach(item => {
            if (item.roleType === ROLE_TYPE.DESIGNATE) {
              const hasFields = this.allUserFields.some(userField => userField.key === item.designateUserSelect);
              !hasFields && (item.designateUserSelect = '');
            } else if (item.roleType === ROLE_TYPE.BP_APPROVER) {
              if (Array.isArray(item.bpDepts) && item.bpDepts.length) {
                item.bpDepts = item.bpDepts.filter(key => this.allDeptFields.some(deptField => deptField.key === key));
              }
              if (Array.isArray(item.bpNames) && item.bpNames.length) {
                item.bpNames = item.bpNames.filter(name => this.BPList.some(BP => BP.name === name));
              }
            } else if (item.roleType === ROLE_TYPE.DESIGNATE_DIRECTOR) {
              if (item.designateDirectorUser && !this.allUserFields.filter(userField => userField.key === item.designateDirectorUser).length) {
                item.designateDirectorUser = '';
                item.designateDirector = '';
              }
            }
          });
        }
        if (designateUserSelect) { // 清除超时任务已删除的人员选择组件 - 指定人员选择字段
          const hasFields = this.allUserFields.some(userField => userField.key === designateUserSelect);
          !hasFields && this.$set(this.approverDrawerData, 'designateUserSelect', '');
        }
        if (designateDirectorUser) { // 清除超时任务已删除的人员选择组件 - 指定人员主管
          const hasFields = this.allUserFields.some(userField => userField.key === designateDirectorUser);
          !hasFields && this.$set(this.approverDrawerData, 'designateDirectorUser', '');
          !hasFields && this.$set(this.approverDrawerData, 'designateDirector', '');
        }
        if (bpDepts) { // 清除超时任务已删除的部门选择组件
          const compareBPDepts = bpDepts.filter(key => this.allDeptFields.some(deptField => deptField.key === key));
          compareBPDepts.length !== bpDepts.length && this.$set(this.approverDrawerData, 'bpDepts', compareBPDepts);
        }
        if (bpNames) { // 清除超时任务已删除的部门选择组件
          const compareBPNames = bpNames.filter(name => this.BPList.some(BP => BP.name === name));
          compareBPNames.length !== bpNames.length && this.$set(this.approverDrawerData, 'bpNames', compareBPNames);
        }
      });
    },
    beforeClose(done) {
      this.approverDrawerData.frontFilterList = (this.approverDrawerData.frontFilterList || []).filter(i => !!i.filterField);
      this.handelError();
      if (this.errorRolesIds.length) {
        ElMessage.error('请检查信息是否填写完整');
        return;
      }
      this.$store.commit('SET_APPROVE_SWITCH', false);
      this.$store.commit('SET_APPROVE_DATA', {});
      done && done();
    },
    oepnDialog() {
      this.$refs.SubmitBtnConfig.open(this.approverDrawerData.submitBtnList);
    },
    initFieldList() {
      const fieldList = [];
      const currentFixedId = `formId_${this.fixedId}`;
      forEachFormOptions(this.customFormList, (element) => {
        if (!['grid', 'titleExplain', 'title', 'createTime', 'createUser', 'workflowId'].includes(element.type)) {
          fieldList.push(element);
        }
        if (element.type === 'subform') {
          element.subform.forEach(subformElement => {
            if (element.options.statistics && element.options.statistics.length && element.options.statistics.includes(subformElement.key)) {
              fieldList.push(subformElement);
            }
          });
        }
        /**
         * 需要排除关联自己的关联表单
         */
        if (element.type === 'linkForm' && element.options.isStatistics && element.options.statistics.length && element.options.remoteParams.id !== currentFixedId) {
          element.subform.forEach(linkElement => {
            if (element.options.statistics.includes(linkElement.key)) {
              fieldList.push(linkElement);
            }
          });
        }
      }, { notForEachSubform: true });
      this.fieldList = fieldList;
    },
    setSubmitBtnConfig(data) {
      this.$set(this.approverDrawerData, 'submitBtnList', data);
    },
    /** change */
    // 超时提醒
    timeoutChange(item) {
      if (item.isOpenTimeOut) {
        this.$set(item, 'timeOut', 24);
        this.$set(item, 'timeOutType', 0);
      } else {
        this.$set(item, 'timeOut', '');
        this.$set(item, 'timeOutType', '');
      }
      this.removeError();
    },
    redirectChange(item) {
      if (item.isRedirectTimeOut) {
        this.$set(item, 'redirectTimeOut', 24);
        this.$set(item, 'timeOutTaskType', 0);
        this.$set(item, 'redirectType', 0);
        this.$set(item, 'transferRoleType', 0);
      } else {
        this.$set(item, 'redirectTimeOut', '');
        this.$set(item, 'timeOutTaskType', '');
        this.$set(item, 'redirectType', 0);
        this.$set(item, 'transferRoleType', '');
      }
      this.removeError();
    },
    // 事件
    handelChangeEvent(item) {
      // 除了请款流程(id:4)，签约内审(id:1023 type: 13)，其他都需要判断事件 “节点之后生成归档编号（id:3） 业务回收合同（id:6）”
      if (![FIXED_PROCESS_TYPE.PAYMENT_APPLY, FIXED_PROCESS_TYPE.SIGN_UP].includes(this.type)) {
        if (item.setEvents.includes(EVENT_TYPE.AFTER_NODE_GENERATE_ARCHIVE_CODE)) { // 节点之后生成归档编号（id:3）
          this.handleEvent(item, EVENT_TYPE.AFTER_NODE_GENERATE_ARCHIVE_CODE);
        }
        if (item.setEvents.includes(EVENT_TYPE.BUSINESS_RECYCLE_CONTRACT)) { // 业务回收合同（id:6）
          this.handleEvent(item, EVENT_TYPE.BUSINESS_RECYCLE_CONTRACT);
        }
      } else if (this.type === FIXED_PROCESS_TYPE.PAYMENT_APPLY && item.setEvents.includes(EVENT_TYPE.OPEN_AUTO_CONFIRM_PAY)) {
        // 请款流程(id:4)，需要判断事件 “自动确认付款（id:5）”只能开启一个
        this.handleEvent(item, EVENT_TYPE.OPEN_AUTO_CONFIRM_PAY);
      }
    },
    handleEvent(item, id) {
      // 去除事件唯一的判断，因为多个条件节点的情况无法判断，只能有用户自己配

      // “节点之后生成归档编号（id:3）”只能一个节点存在
      // const eventNode = this.hasEvent(item, id);
      // const eventNum = eventNode.num;
      // if (eventNum >= 2) {
      //   ElMessage.error(`${eventNode.node ? '节点' + eventNode.node.nodeName : '其他节点'}已开启该事件，无法重复开启`);
      //   item.setEvents.splice(item.setEvents.indexOf(id), 1);
      //   return;
      // }
      if (id === EVENT_TYPE.AFTER_NODE_GENERATE_ARCHIVE_CODE) {
        item.isCountersign = 0; // 选中"节点之后生成归档编号"，不能再选加签
        item.isRequire = 1; // 选中"节点之后生成归档编号"，默认勾选为必选
      }
      if (item.setEvents.includes(EVENT_TYPE.OPEN_AUTO_CONFIRM_PAY)) {
        item.isRequire = 1; // 选中"自动确认付款"，默认勾选为必选
        item.isCountersign = 0;
      }
    },
    setExplanation(explanation, styConfig, type = 0) {
      if (type === 0) {
        this.$set(this.approverDrawerData, 'explanation', explanation);
        this.$set(this.approverDrawerData, 'styConfig', styConfig);
      } else {
        this.$set(this.approverDrawerData, 'approvalExplanation', explanation);
        this.$set(this.approverDrawerData, 'approvalExplanationStyle', styConfig);
      }
    },
    /** tool */
    handelError() {
      this.errorRolesIds = [];
      const approverDrawerData = this.approverDrawerData;
      if (approverDrawerData.examineRoles && approverDrawerData.examineRoles.length) {
        this.approverDrawerData.examineRoles.forEach((i, index) => {
          console.log(i);
          if (!i.roleName) {
            this.errorRolesIds.push({
              type: 'role', id: index, left: 0, class: 'error-role-name', msg: '请输入角色名称'
            });
          }
          if (!i.roleType && i.roleType !== 0) {
            this.errorRolesIds.push({
              type: 'roleType', id: index, left: '172px', msg: '请选择审批角色'
            });
          }
          if (i.roleType === ROLE_TYPE.DEPARTMENT && (!i.departmentIdList || i.departmentIdList.length === 0)) {
            this.errorRolesIds.push({
              type: 'dept', id: index, left: 172 * 2 + 'px', msg: '请选择部门'
            });
          } else if (i.roleType === ROLE_TYPE.CUSTOMIZE && (!i.diyUserIdList || i.diyUserIdList.length === 0)) {
            this.errorRolesIds.push({
              type: 'diyUser', id: index, left: 172 * 2 + 'px', msg: '请选择人员'
            });
          } else if (i.roleType === ROLE_TYPE.DIRECTOR && !i.manageRole && i.manageRole !== 0) {
            this.errorRolesIds.push({
              type: 'manage', id: index, left: 172 * 2 + 'px', msg: '请选择主管类型'
            });
          } else if (i.roleType === ROLE_TYPE.DESIGNATE && !i.designateUserSelect) {
            this.errorRolesIds.push({
              type: ROLE_TYPE.DESIGNATE, id: index, left: 172 * 2 + 'px', msg: '请选择人员选择字段'
            });
          } else if (i.roleType === ROLE_TYPE.ROLE_GROUP && !i.roleGroup) {
            this.errorRolesIds.push({
              type: ROLE_TYPE.ROLE_GROUP, id: index, left: 172 * 2 + 'px', msg: '请选择角色组'
            });
          } else if (i.roleType === ROLE_TYPE.BP_APPROVER) {
            if (!i.bpNames || !i.bpNames.length) {
              this.errorRolesIds.push({
                type: ROLE_TYPE.BP_APPROVER, id: index, left: 172 * 2 + 'px', msg: '请选择BP类型'
              });
            } else if (!i.bpDepts || !i.bpDepts.length) {
              this.errorRolesIds.push({
                type: ROLE_TYPE.BP_APPROVER, id: index, left: 172 * 2 + 150 + 'px', msg: '请选择部门'
              });
            }
          } else if (i.roleType === ROLE_TYPE.ARREARS_USERS && !i.transferRole && i.transferRole !== 0) {
            this.errorRolesIds.push({
              type: ROLE_TYPE.ARREARS_USERS, id: index, left: 172 * 2 + 'px', msg: '请选择指定人员字段'
            });
          } else if (i.roleType === ROLE_TYPE.DESIGNATE_DIRECTOR) {
            if (!i.designateDirectorUser) {
              this.errorRolesIds.push({
                type: ROLE_TYPE.DESIGNATE_DIRECTOR, id: index, left: 172 * 2 + 'px', msg: '请选择人员选择字段'
              });
            } else if (typeof i.designateDirector !== 'number') {
              this.errorRolesIds.push({
                type: ROLE_TYPE.DESIGNATE_DIRECTOR, id: index, left: 172 * 2 + 150 + 'px', msg: '请选择主管类型'
              });
            }
          }
        });
      }
      if (approverDrawerData.isOpenTimeOut && !approverDrawerData.timeOut && approverDrawerData.timeOut !== 0) {
        this.errorRolesIds.push({
          type: 'openTimeOut',
          left: '116px',
          msg: '请输入超时提醒时间'
        });
      }
      if (approverDrawerData.isRedirectTimeOut && !approverDrawerData.redirectTimeOut && approverDrawerData.redirectTimeOut !== 0) {
        this.errorRolesIds.push({
          type: 'redirectTimeOut',
          left: '116px',
          msg: '请输入超时任务时间'
        });
      }
      if (approverDrawerData.isRedirectTimeOut && [1, 2].includes(approverDrawerData.timeOutTaskType)) {
        if (approverDrawerData.transferRoleType === ROLE_TYPE.DEPARTMENT && (!approverDrawerData.transferDepartmentIdList || approverDrawerData.transferDepartmentIdList.length === 0)) {
          this.errorRolesIds.push({
            type: 'transferdept', left: 172 + 'px', msg: '请选择部门'
          });
        } else if (approverDrawerData.transferRoleType === ROLE_TYPE.CUSTOMIZE && (!approverDrawerData.transferDiyUserIdList || approverDrawerData.transferDiyUserIdList.length === 0)) {
          this.errorRolesIds.push({
            type: 'transferdiyUser', left: 172 + 'px', msg: '请选择人员'
          });
        } else if (approverDrawerData.transferRoleType === ROLE_TYPE.DIRECTOR && !approverDrawerData.transferManageRole && approverDrawerData.transferManageRole !== 0) {
          this.errorRolesIds.push({
            type: 'transfermanage', left: 172 + 'px', msg: '请选择主管类型'
          });
        } else if (approverDrawerData.transferRoleType === ROLE_TYPE.DESIGNATE && !approverDrawerData.designateUserSelect) {
          this.errorRolesIds.push({
            type: 'transfer' + ROLE_TYPE.DESIGNATE, left: 172 + 'px', msg: '请选择人员选择字段'
          });
        } else if (approverDrawerData.transferRoleType === ROLE_TYPE.ROLE_GROUP && !approverDrawerData.roleGroup) {
          this.errorRolesIds.push({
            type: 'transfer' + ROLE_TYPE.ROLE_GROUP, left: 172 + 'px', msg: '请选择角色组'
          });
        } else if (approverDrawerData.transferRoleType === ROLE_TYPE.ARREARS_USERS && !approverDrawerData.transferRole && approverDrawerData.transferRole !== 0) {
          this.errorRolesIds.push({
            type: 'transfer' + ROLE_TYPE.ARREARS_USERS, left: 172 + 'px', msg: '请选择指定人员字段'
          });
        } else if (approverDrawerData.transferRoleType === ROLE_TYPE.DESIGNATE_DIRECTOR) {
          if (!approverDrawerData.designateDirectorUser) {
            this.errorRolesIds.push({
              type: 'transfer' + ROLE_TYPE.DESIGNATE_DIRECTOR, left: 172 + 'px', msg: '请选择人员选择字段'
            });
          } else if (!approverDrawerData.designateDirector && approverDrawerData.designateDirector !== 0) {
            this.errorRolesIds.push({
              type: 'transfer' + ROLE_TYPE.DESIGNATE_DIRECTOR, left: 172 * 2 + 'px', msg: '请选择主管类型'
            });
          }
        }
        if (approverDrawerData.transferRoleType === ROLE_TYPE.BP_APPROVER) {
          if (!approverDrawerData.bpNames || !approverDrawerData.bpNames.length) {
            this.errorRolesIds.push({
              type: 'transfer' + ROLE_TYPE.BP_APPROVER, left: 172 + 'px', msg: '请选择BP类型'
            });
          } else if (!approverDrawerData.bpDepts || !approverDrawerData.bpDepts.length) {
            this.errorRolesIds.push({
              type: 'transfer' + ROLE_TYPE.BP_APPROVER, left: 172 * 2 + 'px', msg: '请选择部门'
            });
          }
        }
      }
    },
    getError(type, id) {
      if (this.errorRolesIds.length <= 0) return {};
      return this.errorRolesIds.find(i => i.type === type && ((!id && id !== 0) || i.id === id)) || {};
    },
    removeError() {
      this.errorRolesIds = [];
    },
    copyItem(item) {
      if (this.approverDrawerData.frontFilterList.length >= 20) {
        ElMessage.warning('最多添加20条规则');
        return;
      }
      this.approverDrawerData.frontFilterList.push(_.cloneDeep(item));
    },
    addFilter() {
      if (!this.approverDrawerData.frontFilterList) this.$set(this.approverDrawerData, 'frontFilterList', []);
      if (this.approverDrawerData.frontFilterList.length >= 20) {
        ElMessage.warning('最多添加20条规则');
        return;
      }
      this.approverDrawerData.frontFilterList.push({
        filterField: '',
        math: '=',
        valueType: 0, //  0:值  1:字段
        value: ''
      });
      this.$forceUpdate();
    },
    deleteItem(index) {
      this.approverDrawerData.frontFilterList.splice(index, 1);
    },
    openExplateDialog(item, type = 0) {
      const params = {};
      this.explateDialogTitle = type === 0 ? '节点审批说明' : '审批弹窗说明';
      if (type === 0) {
        params.explanation = item.explanation;
        params.styConfig = item.styConfig;
      } else {
        params.explanation = item.approvalExplanation;
        params.styConfig = item.approvalExplanationStyle;
      }
      this.$refs['explateDialog'].openDialog(params, type);
    },
    // 判断是否存在事件 id
    hasEvent(item, id) {
      let ans = 0;
      let node = null;
      const dfs = (curNode) => {
        if (!curNode || this.isEmpty(curNode)) return;
        if (curNode.setEvents && curNode.setEvents.length && curNode.setEvents.includes(id)) {
          const curNodeId = curNode.id || curNode._id;
          const treeId = item.id || item._id;
          if (curNodeId !== treeId) node = curNode;
          ans++;
        }
        if (!this.isEmpty(curNode.childNode)) {
          dfs(curNode.childNode);
        }
        if (curNode.conditionNodes && curNode.conditionNodes.length) {
          for (let i = 0; i < curNode.conditionNodes.length; i++) {
            dfs(curNode.conditionNodes[i]);
          }
        }
      };
      dfs(this.processList);
      return { node, num: ans };
    },
    isEmpty(obj) {
      if (!obj) return false;
      return Object.keys(obj).length <= 0;
    }
  }
};
</script>

<style lang="scss" scoped>
.title {
  display: flex;
  height: 50px;
  padding: 0 24px;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
  .icon {
    font-size: 18px;
    color: #999;
    cursor: pointer;
  }
}
.content {
  padding: 17px 10px 17px 24px;
  &::v-deep {
    .el-checkbox {
      &.is-checked {
        .check-span {
          color: #333 !important;
          font-weight: bold;
        }
      }
    }
    .el-checkbox__label {
      padding-left: 4px;
    }
  }
  .title-tip {
    font-size: 14px;
    color: #999;
    font-weight: normal;
    margin-left: 6px;
  }
}
.width-160 {
  width: 160px;
  &::v-deep {
    .el-input__inner {
      width: 160px;
    }
    .el-cascader__tags, .el-select__tags {
      width: 130px;
      max-width: 130px !important;
      .el-tag > span {
        max-width: 50px;
      }
    }
    .el-select__tags-text {
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
}
.width-120 {
  width: 120px;
  &::v-deep {
    .el-input__inner {
      width: 120px;
    }
    .el-select__tags-text {
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      padding-right: 3px;
    }
  }
}
.mr12 {margin-right: 12px;}
.ml12 {margin-left: 12px;}
.check-span {
  color: #666;
  font-size: 14px;
}
.width-240 {
  width: 240px;
  &::v-deep {
    .el-input__inner {
      width: 240px;
    }
  }
}
.event-box {
  &::v-deep {
    .el-tag {
      max-width: 12em;
    }
    .el-select__tags-text {
      max-width: 100%;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .el-icon-close:before {
      width: 16px;
    }
  }
}
.isError {
  &::v-deep {
    .el-input__inner {
      border-color: #f56c6c !important;
    }
  }
}
.options-content {
  font-size: 14px;
  text-align: left;
  color: #333333;
  line-height: 1.5;
}
.one-cell {
  display: flex;
  align-items: center;
}
.mt18 {
  margin-top: 18px;
}
.timeout-item {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 16px;
  // min-height: 32px;
  position: relative;
  .checkbox {
    margin-right: 10px;
  }
  &::v-deep {
    .timeout-item-input {
      margin-right: 5px;
    }
  }
  .timeout-tip {
    font-size: 14px;
    margin-right: 5px;
    color: #666;
  }
}
.flex-display {
  display: flex;
  margin-top: 17px;
  width: 100%;
  position: relative;
}
.explanation{
  display: flex;
  align-items: center;
  margin-top: 12px;
  .label {
    font-size: 14px;
    text-align: left;
    color: #999999;
  }
  .explanation-content {
    font-size: 14px;
    max-width: 300px;
    color: #333;
  }
  &::v-deep {
    .el-icon-edit-outline{
      margin-right: 4px;
      color: #333;
    }
  }
}
.error-tool {
  position: absolute;
  height: 20px;
  font-size: 12px;
  bottom: -20px;
  color: #f56c6c;
}
.btn-config {
  display: flex;
  align-items: center;
  .label {
    color: #406eff;
    text-decoration: underline;
  }
  .icon {
    font-size: 14px;
    color: #406eff;
  }
}
::v-deep {
  .el-drawer__body {
    @include scrollBar($x: hidden, $y: scroll);
  }
}
.top-content {
  display: flex;
  border-bottom: 1px solid #EBEEFD;
  margin: 16px 0;
  &::v-deep {
    .el-form-item__label {
      padding-bottom: 0;
      &::before {
        display: none;
      }
    }
  }
  .width100 {
    width: 100%;
    &::v-deep {
      .el-select,.el-input,.el-input__inner {
        width: 100%;
      }
    }
  }
}
.filter-item {
  display: flex;
  margin-bottom: 25px;
  &.last {
    margin-bottom: 0;
  }
  &::v-deep {
    .select-field {
      width: 160px !important;
      .el-input__inner {
        width: 160px !important;
      }
    }
  }
}
.footer-bar {
  display: flex;
  align-items: center;
  margin-top: 16px;
  .add-btn {
    font-size: 14px;
    color: #406eff;
    cursor: pointer;
    margin-right: 12px;
    font-weight: bold;
    .add-icon {
      font-size: 12px;
    }
  }
  .tip {
    font-size: 12px;
    color: #999;
  }
}
.filter-scroll {
  max-height: 160px;
  @include scrollBar($x: hidden, $y: auto);
  .btn-list {
    display: flex;
    align-items: center;
    .delete-icon {
      width: 12px;
      cursor: pointer;
      margin-left: 9px;
    }
    .copy-icon {
      width: 12px;
      cursor: pointer;
      margin-left: 9px;
    }
  }
}
</style>
